<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getRoles">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="clearSearch">重置查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增角色</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAssign">分配角色</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="roles" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="sn" label="角色编号" width="120" sortable>
            </el-table-column>
            <el-table-column prop="name" label="角色名称" width="120" sortable>
            </el-table-column>
            <el-table-column prop="descs" label="角色描述" width="300" sortable>
            </el-table-column>
            <el-table-column prop="permissions" label="持有权限" width="400" sortable :formatter="formatState">
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <el-col :span="24" class="toolbar">
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                           :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--修改的时候 弹出 编辑界面-->
        <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="角色编号" prop="sn">
                    <el-input v-model="editForm.sn" auto-complete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="descs">
                    <el-input v-model="editForm.descs" auto-complete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="权限处理" prop="permissions">
                    <el-transfer v-model="selectedPermissions"
                                 :data="allPermissions"
                                 :titles='titles'
                                 :props="{
                                         key:'id',
                                         label:'name'
                                         }"
                                 @change="handleChange">
                    </el-transfer>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" width="60%" :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="130px" :rules="addFormRules" ref="addForm">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="角色编号" prop="sn">
                    <el-input v-model="addForm.sn" auto-complete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="descs">
                    <el-input v-model="addForm.descs" auto-complete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="权限处理" prop="permissions">
                    <el-transfer v-model="selectedPermissions"
                                 :data="allPermissions"
                                 :titles='titles'
                                 :props="{
                                         key:'id',
                                         label:'name'
                                         }"
                                 @change="handleChange">
                    </el-transfer>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--分配角色界面-->
        <el-dialog title="角色绑定" width="60%" :visible.sync="assignFormVisible" :close-on-click-modal="false">
            <el-form :model="assignForm" label-width="130px" ref="assignForm">
                <el-form-item label="员工">
                    <el-select v-model="assignForm.id" placeholder="请选择员工"
                               style="width:100%">
                        <el-option v-for="item in employeeSelect" :key="item.id"
                                   :label="item.realName+'  工号:'+item.employeeNumber"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="assignForm.role.id" placeholder="请选择角色"
                               style="width:100%">
                        <el-option v-for="item in roleSelect" :key="item.id"
                                   :label="item.name"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="assignFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="assignSubmit" :loading="assignLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    export default {
        data() {
            return {
                /*角色列表*/
                roles: [],
                user: '',
                filters: {
                    name: ''
                },
                /*每页条数*/
                pageSize: 5,
                /*当前页*/
                currentPage: 1,
                /*总数*/
                total: 0,
                sels: [],//列表选中列
                listLoading: false,//等于false显示加载中效果
                editLoading: false,//修改加载中
                addLoading: false,//新增加载
                assignLoading: false,
                roles: [],
                editFormVisible: false,//默认不显示对话框
                addFormVisible: false,
                assignFormVisible: false,
                /*穿梭框标题*/
                titles: ["所有权限", "已选权限"],
                /*所有权限栏数据*/
                allPermissions: [],
                /*已选权限栏数据*/
                selectedPermissions: [],
                /*员工下拉框*/
                employeeSelect: [],
                /*角色下拉框*/
                roleSelect: [],
                /*修改表单*/
                editForm: {
                    id: 0,
                    name: '',
                    sn: '',
                    descs: '',
                },
                /*分配表单*/
                assignForm: {
                    id: '',
                    role: {
                        id: ''
                    }
                },
                /*修改表单验证*/
                editFormRules: {
                    name: [
                        {required: true, message: '请输入角色名', trigger: 'blur'}
                    ],
                    sn:
                        [
                            {required: true, message: '请输入角色编号', trigger: 'blur'}
                        ]
                }
                ,
                /*添加表单*/
                addForm: {
                    name: '',
                    sn:
                        '',
                    descs:
                        '',
                }
                ,
                /*添加表单验证*/
                addFormRules: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    sn:
                        [
                            {required: true, message: '请输入角色编号', trigger: 'blur'}
                        ]
                }
                ,
            }
        },
        methods: {
            /*员工下拉框数据*/
            selectEmployee(tenantId) {
                this.$http.get('/employee/list/' + tenantId).then(res => {
                    this.employeeSelect = res.data;
                });
            },
            /*角色下拉框数据*/
            selectRole(tenantId) {
                this.$http.get('/role/list/' + tenantId).then(res => {
                    this.roleSelect = res.data;
                });
            },
            /*权限格式转换*/
            formatState: function (row, column) {
                let perms = [];
                for (let i = 0; i < row.permissions.length; i++) {
                    perms.push(row.permissions[i].name);
                }
                return JSON.stringify(perms)
            },
            /*穿梭框移动值时触发函数*/
            handleChange(value, direction, movedKeys) {
                this.selectedPermissions = value;
            },
            /*重置查询*/
            clearSearch() {
                this.filters.name = "";
                this.getRoles();
            },
            //打开编辑窗口时处理值
            handleEdit(index, row) {
                //打开修改的对话框
                this.editFormVisible = true;
                //回显
                this.editForm = row;
                /*权限的回显 先清空*/
                this.selectedPermissions = [];
                for (let i = 0; i < row.permissions.length; i++) {
                    this.selectedPermissions.push(row.permissions[i].id);
                }
            },
            //打开新增窗口时处理值
            handleAdd: function () {
                /*清空表单*/
                this.addForm.name = ''
                this.addForm.sn = ''
                this.addForm.descs = ''
                this.selectedPermissions = []
                //弹出表单
                this.addFormVisible = true;
            },
            //打开分配窗口时处理值
            handleAssign: function () {
                this.assignForm.id=''
                this.assignForm.role.id=''
                this.assignFormVisible = true;
            },
            /*页面跳转*/
            handleCurrentChange(val) {
                //当前页
                this.currentPage = val;
                this.getRoles();
            },
            //角色列表
            getRoles() {
                /*请求参数*/
                let params = {
                    /*当前页*/
                    currentPage: this.currentPage,
                    /*每页条数*/
                    pageSize: 5,
                    /*高级查询字段*/
                    name: this.filters.name
                    /*租户id在后台拿*/
                }
                /*显示加载中状态*/
                this.listLoading = true;
                this.$http.patch('/role/queryPage', params).then((res) => {
                    this.listLoading = false;
                    //判断是否成功
                    if (res.data.hasOwnProperty("success")) {
                        let {msg} = res.data;
                        this.$message({
                            message: msg,
                            type: 'error'
                        });
                    } else {
                        this.total = res.data.total;
                        this.roles = res.data.rows;
                    }
                });
            },
            //权限列表
            getPermissions() {
                /*显示加载中状态*/
                this.listLoading = true;
                /*租户id在后台拿*/
                this.$http.patch('/permission/findAllByRoleId').then((res) => {
                    this.allPermissions = res.data;
                    this.listLoading = false;
                });
            },
            //新增方法
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            /*显示加载效果*/
                            this.addLoading = true;
                            /*表单值提取*/
                            let para = Object.assign({}, this.addForm);
                            /*已选权限的赋值*/
                            para.permissions = [];
                            let permissions = {};
                            for (let i = 0; i < this.selectedPermissions.length; i++) {
                                permissions = {"id": this.selectedPermissions[i]};
                                para.permissions.push(permissions);
                            }
                            /*租户id在后台拿*/
                            this.$http.put('/role/save', para).then((res) => {
                                /*解构*/
                                let {success, msg} = res.data;
                                this.addLoading = false;
                                //判断是否成功
                                if (success) {
                                    this.$message({
                                        message: msg,
                                        type: 'success'
                                    });
                                    /*清空表单*/
                                    this.$refs['addForm'].resetFields();
                                    this.addFormVisible = false;
                                    /*刷新角色列表*/
                                    this.getRoles();
                                    /*刷新角色下拉框*/
                                    this.selectRole(this.user.tenant.id);
                                } else {
                                    this.$message({
                                        message: msg,
                                        type: 'error'
                                    });
                                }
                            });
                        });
                    }
                });
            },
            //分配方法
            assignSubmit: function () {
                this.$refs.assignForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            /*显示加载效果*/
                            this.assignLoading = true;
                            /*表单值提取*/
                            let para = Object.assign({}, this.assignForm);
                            console.debug(para);
                            this.$http.post('/employee/employeeBindRole', para).then((res) => {
                                /*解构*/
                                let {success, msg} = res.data;
                                this.assignLoading = false;
                                //判断是否成功
                                if (success) {
                                    this.$message({
                                        message: msg,
                                        type: 'success'
                                    });
                                    /*清空表单*/
                                    this.$refs['assignForm'].resetFields();
                                    this.assignFormVisible = false;
                                } else {
                                    this.$message({
                                        message: msg,
                                        type: 'error'
                                    });
                                }
                            });
                        });
                    }
                });
            },
            //修改方法
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            /*显示加载效果*/
                            this.editLoading = true;
                            /*表单值提取*/
                            let para = Object.assign({}, this.editForm);
                            /*已选权限的赋值*/
                            para.permissions = [];
                            let permissions = {};
                            for (let i = 0; i < this.selectedPermissions.length; i++) {
                                permissions = {"id": this.selectedPermissions[i]};
                                para.permissions.push(permissions);
                            }
                            /*租户id在后台拿*/
                            this.$http.post('/role/update', para).then((res) => {
                                /*解构*/
                                let {success, msg} = res.data;
                                this.editLoading = false;
                                //判断是否成功
                                if (success) {
                                    this.$message({
                                        message: msg,
                                        type: 'success'
                                    });
                                    /*清空表单*/
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    /*刷新数据*/
                                    this.getRoles();
                                    /*刷新角色下拉框*/
                                    this.selectRole(this.user.tenant.id);
                                } else {
                                    this.$message({
                                        message: msg,
                                        type: 'error'
                                    });
                                }
                            });
                        });
                    }
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.delete('/role/delete/' + row.id).then((res) => {
                        let {success, msg} = res.data;
                        this.listLoading = false;
                        if (success) {
                            this.$message({
                                message: msg,
                                type: 'success'
                            });
                            this.getRoles();
                        } else {
                            this.$message({
                                message: msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {

                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            }
        },
        mounted() {
            /*当前登录用户*/
            this.user = JSON.parse(sessionStorage.getItem('user'));
            /*角色列表*/
            this.getRoles();
            /*权限列表*/
            this.getPermissions();
            /*员工下拉框数据*/
            this.selectEmployee(this.user.tenant.id);
            /*角色下拉框数据*/
            this.selectRole(this.user.tenant.id);
        }
    }

</script>

<style scoped>

</style>